Cousins in binary tree [DFS]¶
Time: O(N); Space: O(H); easy
In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
Return true if and only if the nodes corresponding to the values x and y are cousins.
Example 1:
    1
   / \
  2   3
 /
4
Input: root = {treeNode} [1,2,3,4], x = 4, y = 3
Output: False
Example 2:
  1
 / \
2   3
 \   \
  4   5
Input: root = {treeNode} [1,2,3,null,4,null,5], x = 5, y = 4
Output: True
Example 3:
  1
 / \
2   3
 \
  4
Input: root = {treeNode} [1,2,3,null,4], x = 2, y = 3
Output: False
Constraints:
- The number of nodes in the tree will be between 2 and 100. 
- Each node has a unique integer value from 1 to 100. 
[1]:
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
1. Depth First Search¶
[2]:
class Solution1(object):
    """
    Time: O(N)
    Space: O(H)
    """
    def isCousins(self, root, x, y):
        """
        :type root: TreeNode
        :type x: int
        :type y: int
        :rtype: bool
        """
        def dfs(root, x, depth, parent):
            if not root:
                return False
            if root.val == x:
                return True
            depth[0] += 1
            prev_parent, parent[0] = parent[0], root
            if dfs(root.left, x, depth, parent):
                return True
            parent[0] = root
            if dfs(root.right, x, depth, parent):
                return True
            parent[0] = prev_parent
            depth[0] -= 1
            return False
        depth_x, depth_y = [0], [0]
        parent_x, parent_y = [None], [None]
        return dfs(root, x, depth_x, parent_x) and \
               dfs(root, y, depth_y, parent_y) and \
               depth_x[0] == depth_y[0] and \
               parent_x[0] != parent_y[0]
[3]:
s = Solution1()
root = TreeNode(1)
root.left, root.right = TreeNode(2), TreeNode(3)
root.left.left = TreeNode(4)
x = 4
y = 3
assert s.isCousins(root, x, y) == False
root = TreeNode(1)
root.left, root.right = TreeNode(2), TreeNode(3)
root.left.right = TreeNode(4)
root.right.right = TreeNode(5)
x = 5
y = 4
assert s.isCousins(root, x, y) == True
root = TreeNode(1)
root.left, root.right = TreeNode(2), TreeNode(3)
root.left.right = TreeNode(4)
x = 2
y = 3
assert s.isCousins(root, x, y) == False
Related problems:¶
https://leetcode.com/problems/binary-tree-level-order-traversal/